import { cloud, CloudDB, CloudDBCollection } from '@hw-agconnect/cloud-server';
import { DBUtil } from '../Methods/DBUtil'
import { TbUserDrugType, TbDrugType, TbDrugAndType, TbUserDrug } from '../DBModels/DBModel'

export class DrugTypeServer {
  private static ZONENAME: string = "YaoBox";

  /**
   * 获取用户的药品类型
   * @param userID
   * @returns
   */
  public static async GetDrugTypeListAsync(userID: string): Promise<string[]> {
    console.info(userID)
    let result: string[] = [];
    const db: CloudDB = cloud.database({ zoneName: this.ZONENAME });
    const userDrugTypeList: TbUserDrugType[] = await db
      .collection(TbUserDrugType)
      .query()
      .contains("UserID", userID)
      .get()
    if (userDrugTypeList.length == 0) {
      throw new Error('用户没有添加药品类型');
    }
    const typeList: TbDrugType[] = await db
      .collection(TbDrugType)
      .query()
      .in("id", userDrugTypeList.map(x => {
        return Number.parseFloat(x.DrugTypeID);
      }))
      .get()
    result = typeList.map(x => x.Name)
    return result;
  }

  /**
   * 给用户添加药品类型（类型在类型库中没有时，会自动添加新类型）
   * @param userID 用户名字
   * @param drugTypeName
   * @returns
   */
  public static async AddDrugTypeFromUserAsync(userID: string, drugTypeName: string): Promise<string> {
    const db: CloudDB = cloud.database({ zoneName: this.ZONENAME });
    let typeList: TbDrugType[] = await db
      .collection(TbDrugType)
      .query()
      .equalTo("Name", drugTypeName)
      .get()
    let typeID: number = -1;
    if (typeList.length == 0) {
      let temp: TbDrugType = new TbDrugType();
      temp.Name = drugTypeName;
      await db
        .collection(TbDrugType)
        .insert(temp)
      typeList = await db
        .collection(TbDrugType)
        .query()
        .equalTo("Name", drugTypeName)
        .get()
    }
    typeID = typeList[0].id;
    let userDrugTypeList: TbUserDrugType[] = await db
      .collection(TbUserDrugType)
      .query()
      .contains("UserID", userID)
      .equalTo("DrugTypeID", `${typeID}`)
      .get()
    if (userDrugTypeList.length == 0) {
      let temp: TbUserDrugType = new TbUserDrugType();
      temp.UserID = userID;
      temp.DrugTypeID = `${typeID}`
      await db
        .collection(TbUserDrugType)
        .insert(temp)
    } else {
      return "药品类型已经存在"
    }
    return "成功添加";
  }

  /**
   * 更新药品类型
   * （查询类型中是否已经存在，没有存在的情况下，新建一个药品类型，如果存在直接更新ID）
   * @param userID
   * @param drugTypeName
   * @returns
   */
  public static async UpdateDrugTypeNameAsync(userID: string, drugTypeName: string): Promise<boolean> {

    return true;
  }

  /**
   * 删除用户对应的药品类型
   * @param userID
   * @param drugTypeName
   * @returns
   */
  public static async DeleteUserDrugTypeAsync(userID: string, drugTypeName: string): Promise<string> {
    const db: CloudDB = cloud.database({ zoneName: this.ZONENAME });
    let typeList: TbDrugType[] = await db
      .collection(TbDrugType)
      .query()
      .equalTo("Name", drugTypeName)
      .get()
    if (typeList.length == 0) {
      return "药品类型不存在";
    }
    let temp: TbUserDrugType = new TbUserDrugType();
    temp.UserID = userID;
    temp.DrugTypeID = `${typeList[0].id}`;
    await db
      .collection(TbUserDrugType)
      .delete(temp)
    return "成功删除";
  }

  /**
   * 删除用户对应的药品类型
   * @param userID
   * @param drugTypeName
   * @returns
   */
  public static async DeleteUserDrugTypesAsync(userID: string, drugTypeName: string[]): Promise<string> {
    //添加进去一起查出来,省去反复查询
    drugTypeName.push("未分类");
    let typeList: TbDrugType[] = await DBUtil.QueryAsync(TbDrugType, async (x) => {
      return await x.in("Name", drugTypeName);
    })
    let unfiledType: TbDrugType = typeList.find(x => x.Name === "未分类");
    let drugModels: TbUserDrug[] = await DBUtil.QueryEqualToAsync(TbUserDrug, "UserID", userID);
    let userDrugTypes: TbDrugAndType[] = await DBUtil.QueryAsync(TbDrugAndType, async (x) => {
      return await x.in("UserDrugID", drugModels.map(x => x.id))
        .in("DrugType", typeList.filter(x => x.Name != "未分类").map(x => x.id))
    })
    userDrugTypes = userDrugTypes.map(x => {
      x.DrugType = unfiledType.id
      return x;
    })
    //更新已有药品中的数据,变成未分类
    DBUtil.UpdateAsync(TbDrugAndType, userDrugTypes)
    //删除中间类型表
    let usertypes: TbUserDrugType[] = await DBUtil.QueryAsync(TbUserDrugType, async (x) => {
      return await x.equalTo("UserID", userID)
        .in("DrugTypeID", typeList.filter(x => x.Name != "未分类").map(x => `${x.id}`))
    })
    let result = await DBUtil.DeleteAsync(TbUserDrugType, usertypes)
    return "成功删除";
  }
}